package com.faf.tools;

import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Properties;

/**
 * RSA 是非对称的密码算法，密钥分公钥和私钥，公钥用来加密，私钥用于解密
 */

public class RSAUtils {

	private static String publicKey = null;
	private static String privateKey = null;

	static {
		try {
			Properties p = new Properties();
			p.load(RSAUtils.class.getResourceAsStream("keys.properties"));

			publicKey = p.getProperty("public_key");
			privateKey = p.getProperty("private_key");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生成密钥对：密钥对中包含公钥和私钥
	 * 
	 * @return 包含 RSA 公钥与私钥的 keyPair
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static KeyPair getKeyPair() {
		try {
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); // 获得RSA密钥对的生成器实例
			SecureRandom secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes("utf-8")); // 说的一个安全的随机数
			keyPairGenerator.initialize(2048, secureRandom); // 这里可以是1024、2048 初始化一个密钥对
			KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 获得密钥对
			return keyPair;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} // 获得RSA密钥对的生成器实例
	}

	/**
	 * 获取公钥 (并进行Base64编码，返回一个 Base64 编码后的字符串)
	 * 
	 * @param keyPair
	 * @return 返回一个 Base64 编码后的公钥字符串
	 */
	public static String getPublicKey(KeyPair keyPair) {
		PublicKey publicKey = keyPair.getPublic();
		byte[] bytes = publicKey.getEncoded();
		return Base64.getEncoder().encodeToString(bytes);
	}

	/**
	 * 获取私钥(并进行Base64编码，返回一个 Base64 编码后的字符串)
	 * 
	 * @param keyPair
	 * @return 返回一个 Base64 编码后的私钥字符串
	 */
	public static String getPrivateKey(KeyPair keyPair) {
		PrivateKey privateKey = keyPair.getPrivate();
		byte[] bytes = privateKey.getEncoded();
		return Base64.getEncoder().encodeToString(bytes);
	}

	/**
	 * 将Base64编码后的公钥转换成 PublicKey 对象
	 * 
	 * @param pubStr
	 * @return PublicKey
	 */
	private static PublicKey string2PublicKey(String pubStr) {
		try {
			byte[] bytes = Base64.getDecoder().decode(pubStr);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
			KeyFactory keyFactory;
			keyFactory = KeyFactory.getInstance("RSA");
			PublicKey publicKey = keyFactory.generatePublic(keySpec);
			return publicKey;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将Base64编码后的私钥转换成 PrivateKey 对象
	 * 
	 * @param priStr
	 * @return PrivateKey
	 */
	private static PrivateKey string2Privatekey(String priStr) {
		try {
			byte[] bytes = Base64.getDecoder().decode(priStr);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
			KeyFactory keyFactory;
			keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
			return privateKey;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 公钥加密
	 * 
	 * @param content   待加密的内容 byte[]
	 * @param publicKey 加密所需的公钥对象 PublicKey
	 * @return 加密后的字节数组 byte[]
	 */
	public static String publicEncrytype(String content, String publicKey) {
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, string2PublicKey(publicKey));
			byte[] bytes = cipher.doFinal(content.getBytes("UTF-8"));
			return Base64.getEncoder().encodeToString(bytes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 私钥解密
	 * 
	 * @param content    待解密的内容 byte[]
	 * @param privateKey 解密需要的私钥对象 PrivateKey
	 * @return 解密后的字节数组 byte[]
	 */
	public static String privateDecrypt(String content, String privateKey) {
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, string2Privatekey(privateKey));
			return new String(cipher.doFinal(Base64.getDecoder().decode(content.getBytes())), "utf-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public static String publicEncrytype(String content) {
		return publicEncrytype(content, publicKey);
	}
	
	public static String privateDecrypt(String content) {
		return privateDecrypt(content, privateKey);
	}
}